import 'dart:convert' as convert;
import 'dart:convert';

import 'package:flutter/services.dart' show rootBundle;
import 'package:encrypt/encrypt.dart';


import 'package:fluttermodule/color/MyDeEncrypt.dart';
//
enum EncryptionState{
  original,//POST参数原始
  noEncryption,//POST参数不加密
  encryption,//POST参数加密
}
class MyEncrypt{
  static Future <Map> encryptionParams(Map map,EncryptionState state) async{
    var allParams = Map();
    allParams.addAll(map);
    Map header = MyEncrypt.headers();
    allParams.addAll(header);
    switch (state){
      case EncryptionState.original:
        allParams.addAll(map);
        break;
      case EncryptionState.noEncryption:
        String jsonString = convert.jsonEncode(allParams);
        allParams = {"code" : 1, "data" :jsonString};
        break;
      case EncryptionState.encryption:
        String jsonString = convert.jsonEncode(allParams);
        String encode = await MyEncrypt.encodeString(jsonString);
        allParams = {"code" : 2, "data" :encode};
        break;
    }
    return await allParams;
  }
  static Future<String> decodeString(String content) async{
    return MyDeEncrypt.decodeString(content);
  }
  static Future<String> encodeString(String content) async{

    var publicKeyStr = await rootBundle.loadString('assets/data/rsa_public_key.pem');
    var publicKey = RSAKeyParser().parse(publicKeyStr);
    final encrypter = Encrypter(RSA(publicKey: publicKey));

    List<int> sourceBytes = utf8.encode(content);
    int inputLen = sourceBytes.length;
    int maxLen = 117;
    List<int> totalBytes = List();
    for (var i = 0; i < inputLen; i += maxLen) {
      int endLen = inputLen - i;
      List<int> item;
      if (endLen > maxLen) {
        item = sourceBytes.sublist(i, i + maxLen);
      }
      else {
        item = sourceBytes.sublist(i, i + endLen);
      }
      totalBytes.addAll(encrypter.encryptBytes(item).bytes);
    }
    return base64.encode(totalBytes);
  }
  static Map headers(){
    var map = Map();
    map.addAll({"bundleId":"com.seeksth.seeks"});
    map.addAll({"uuid":"6DF01073-C68D-48B0-B09A-E107A759AE43"});
    map.addAll({"channel":"debug"});
    map.addAll({"packageName":"com.seeksth.seeks"});
    map.addAll({"from":201});
    map.addAll({"rawChannel":"default"});
    map.addAll({"versionCode":16});
    map.addAll({"model":"x86_64"});
    map.addAll({"osv":"iOS12.4"});
    map.addAll({"mac":""});
    return map;
  }
}
